//
//  CLHomeWeather.m
//  CareLink
//
//  Created by 刘家强 on 16/8/18.
//  Copyright © 2016年 Seven Team. All rights reserved.
//

#import "CLHomeWeather.h"
#import "CLHomeWeatherListCity.h"
#import "DXPopover.h"

//百度天气key
#define kBDWeather_KEY @"17IvzuqmKrK1cGwNL6VQebF9"
#define kGetWeather_URL(city) ([NSString stringWithFormat:@"http://api.map.baidu.com/telematics/v3/weather?location=%@&output=json&ak=%@", city, kBDWeather_KEY])

@interface CLHomeWeather ()

@property (nonatomic, strong) NSDictionary *weatherDataDict;
@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet UILabel *iconLabel;
@property (weak, nonatomic) IBOutlet UIButton *cityBut;
@property (weak, nonatomic) IBOutlet UILabel *temperatureLabel;
@property (weak, nonatomic) IBOutlet UILabel *dateLabel;
@property (nonatomic, strong) DXPopover *popover;

@end

@implementation CLHomeWeather

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    [self setupUI];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(typeButtonClick:) name:@"kTypeButtonClick" object:nil];
}

- (void)setupUI {
    NSString *city = [self readUserAccount];

    // 判断是否已经储存
    if (city == nil) {
        city = @"北京市";
    }

    [self loadWeatherData:city];
    [self loadDate];
}
- (IBAction)cityButClick:(UIButton *)sender {
    [self titleShowPopover];
}

- (void)titleShowPopover {
    self.popover = [DXPopover new];
    self.popover.maskType = DXPopoverMaskTypeBlack;
    self.popover.contentInset = UIEdgeInsetsZero;
    self.popover.backgroundColor = [UIColor whiteColor];
    UIView *typeView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 400)];
    typeView.backgroundColor = [UIColor clearColor];

    // 设置起始点的位置
    CGPoint start = self.cityBut.center;
    start.y += 80;

    [self.popover showAtPoint:start
               popoverPostion:DXPopoverPositionDown
              withContentView:typeView
                       inView:[self.view window]];

    CLHomeWeatherListCity *vc = [[CLHomeWeatherListCity alloc] init];

    [self.popover addSubview:vc.view];
    [self addChildViewController:vc];

    vc.view.translatesAutoresizingMaskIntoConstraints = NO;

    [vc.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(10);
        make.left.offset(10);
        make.width.offset(280);
        make.height.offset(380);
        //        make.edges.offset(10);
        //                make.edges.offset(0);
    }];
}

- (void)loadDate {
    // 这个是NSDate类型的日期，所要获取的年月日都放在这里；
    NSDate *date = [NSDate date];
    
    // 获取当前时间
    NSCalendar *cal = [NSCalendar currentCalendar];

    //这句是说你要获取日期的元素有哪些。获取年就要写NSYearCalendarUnit，获取小时就要写NSHourCalendarUnit，中间用|隔开；
    unsigned int unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;

    NSDateComponents *d = [cal components:unitFlags fromDate:date];    //把要从date中获取的unitFlags标示的日期元素存放在NSDateComponents类型的d里面；
    //然后就可以从d中获取具体的年月日了；
    NSLog(@"%@", [NSString stringWithFormat:@"%ld年%ld月%ld日", d.year, d.month, d.day]);
    self.dateLabel.text = [NSString stringWithFormat:@"%ld年%ld月%ld日", d.year, d.month, d.day];
}

- (void)loadWeatherData:(NSString *)city {
    NSString *urlString = kGetWeather_URL(city);

    // 百分号转义
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

    //通过AFN 创建网络管理，发送网络请求
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    [manager GET:urlString parameters:nil progress:^(NSProgress *_Nonnull downloadProgress) {
    }
        success:^(NSURLSessionDataTask *_Nonnull task, id _Nullable responseObject) {

            NSDictionary *dict = (NSDictionary *)responseObject;

            if (dict[@"results"]) {
                self.weatherDataDict = dict;

                //获取数据了，直接给控件赋值
                NSDictionary *dateDict = dict[@"results"][0][@"weather_data"][0];

                //1 温度
                NSString *temper = dateDict[@"temperature"];
                NSLog(@"温度 %@", temper);
                self.temperatureLabel.text = [@"温度 " stringByAppendingString:temper];
                //2 天气
                NSString *weather = dateDict[@"weather"];
                NSLog(@"天气 %@", weather);
                self.iconLabel.text = weather;

                if ([weather isEqualToString:@"雷阵雨"]) {
                    self.iconView.image = [UIImage imageNamed:@"thunder_mini"];
                } else if ([weather isEqualToString:@"晴"]) {
                    self.iconView.image = [UIImage imageNamed:@"sun_mini"];
                } else if ([weather isEqualToString:@"多云"]) {
                    self.iconView.image = [UIImage imageNamed:@"sun_and_cloud_mini"];
                } else if ([weather isEqualToString:@"阴"]) {
                    self.iconView.image = [UIImage imageNamed:@"nosun_mini"];
                } else if ([weather isEqualToString:@"雨"]) {
                    self.iconView.image = [UIImage imageNamed:@"rain_mini"];
                } else if ([weather isEqualToString:@"雪"]) {
                    self.iconView.image = [UIImage imageNamed:@"snow_heavyx_mini"];
                } else {
                    self.iconView.image = [UIImage imageNamed:@"sand_float_mini"];
                }

                //3 城市
                NSString *city = dict[@"results"][0][@"currentCity"];
                NSLog(@"%@", city);

                [self saveUserAccountWithCity:city];

                // but 添加下划线
                NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:city];
                NSRange strRange = {0, [str length]};
                [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange];
                [self.cityBut setAttributedTitle:str forState:UIControlStateNormal];
            }

        }
        failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {

            NSLog(@"网络错误");
        }];
}

/**
 *  保存用户账户
 */
- (void)saveUserAccountWithCity:(NSString *)city {
    [[NSUserDefaults standardUserDefaults] setObject:city forKey:@"city"];

    // 在 iOS8 之后就不需要了
    // [[NSUserDefaults standardUserDefaults] synchronize];
}

- (NSString *)readUserAccount {
    NSString *city = [[NSUserDefaults standardUserDefaults] stringForKey:@"city"];
    return city;
}

// 城市按钮点击
- (void)typeButtonClick:(id)sender {
    //    NSLog(@"%@",[sender object]);
    NSString *city = [sender object];

    [self.cityBut setTitle:city forState:UIControlStateNormal];
    [self loadWeatherData:city];

    [self.popover dismiss];
}

#pragma mark - 懒加载
- (NSDictionary *)weatherDataDict {
    if (_weatherDataDict == nil) {
        _weatherDataDict = [NSDictionary dictionary];
    }
    return _weatherDataDict;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
